<template>
    <div>
        <home-header ref="homeHeader" :nav="nav" :logo="logoInfo" :showBack="true" :showLogin="false"></home-header>
        <ul class="content-list">
            <div class="success-tips">
                <span class="sport-success sport" v-if="isSuccess"></span>
                <span class="sport-error sport" v-if="!isSuccess"></span>
                <span class="success" v-if="isSuccess">链接成功 {{count}}在线</span>
                <span class="error" v-if="!isSuccess">链接断开</span>
            </div>
            <template v-for="(item, index) in list">
                <li v-if="item.ID" :key="index">
                    <div class="title">{{ item.cretedUser }}</div>
                    <div class="time">{{ item.addtime }}</div>
                    <div class="content" @click="copy(item.content)">{{ item.content }}</div>
                </li>
            </template>
        </ul>
        <div class="ipt-box">
            <el-input type="textarea" v-model="msg" rows="3" @keyup.enter="sendMsg" placeholder="请输入消息"
                class="chat-input">
            </el-input>
        </div>
        <div class="btn-box">
            <el-upload class="upload-demo" action="#" :show-file-list="false" :auto-upload="false"
                :on-change="onChange">
                <el-button type="primary">文件上传</el-button>
            </el-upload>
            <el-button type="primary" @click="sendMsg" class="chat-btn">发送</el-button>
        </div>
        <public-footer :userInfo="logoInfo" :links="links"></public-footer>
        <scoll-top></scoll-top>
    </div>
</template>
<script>
import HomeHeader from '~/components/home-header/index.vue';
import request from '~/request/request';
import mixins from '~/mixins/mixins';
import publicFooter from "~/components/public-footer/index.vue";
import scollTop from "~/components/scoll-top/index.vue";
import setting from "../config/setting.js"
import { showToast } from '../utils/index';
export default {
    name: 'ChatPage',
    mixins: [mixins],
    components: {
        HomeHeader,
        publicFooter,
        scollTop
    },
    async asyncData({ app }) {
        try {
            let nav = await request('/api/index/getNav');
            let logoInfo = await request('/api/index/getBlogTitle');
            let links = await request('/api/index/getLink');
            return {
                nav: nav.data,
                logoInfo: logoInfo.data,
                links: links.data
            }
        } catch (error) {
            console.log(error);
        }
    },
    data() {
        return {
            nav: [],
            logoInfo: {},
            links: [],
            msg: '',
            ws: null,
            fileList: [],
            list: [],
            isSuccess: false,
            count : 0
        }
    },
    mounted() {
        this.initSocket();
        this.queryMessage();
    },
    methods: {
        initSocket() {
            if (!window.WebSocket) return;
            this.ws = new WebSocket(setting.wsUrl + '/api/webChat/chat');
            this.ws.onopen = () => {
                this.isSuccess = true;
            }
            this.ws.onmessage = (e) => {
                let data = JSON.parse(e.data);
                this.list.push(data.data);
                this.count = data.data.count || 0;
                // 滚动到最后
                this.$nextTick(() => {
                    let el = document.querySelector('.content-list');
                    el.scrollTop = el.scrollHeight;
                })
            }
            this.ws.onclose = () => {
                setTimeout(() => {
                    this.initSocket()
                }, 2000)
                this.isSuccess = false;
            }
            this.ws.onerror = () => {
                this.isSuccess = false;
                setTimeout(() => {
                    this.initSocket()
                }, 2000)
            }
        },
        sendMsg() {
            if (!this.ws) {
                showToast({
                    msg: "还没有链接上ws",
                    type: "error"
                })
                return;
            }
            if (!this.msg) {
                showToast({
                    msg: "消息内容为空",
                    type: "error"
                })
            }
            this.ws.send(this.msg);
            this.msg = '';
        },
        onChange(e) {
            let formData = new FormData();
            formData.append('file', e.raw);
            formData.append('FilePath', '../upload/chatImg')
            request({
                url: "/api/upload",
                method: "post",
                uplodFile: true,
                data: formData,
                success: (res) => {
                    this.ws.send(
                        this.msg + JSON.stringify({
                            tips: "文件信息-" + e.name,
                            message: res.data.baseUrl + 'chatImg/' + res.data.fileName
                        })
                    )
                }
            })
        },
        /**复制*/
        copy(text) {
            let input = document.createElement('input');
            input.value = text;
            document.body.appendChild(input);
            input.select();
            document.execCommand('copy');
            document.body.removeChild(input);
            showToast({
                msg: "复制成功",
                type: "success"
            })
        },
        /**查询最近消息*/
        queryMessage() {
            request({
                url: "/api/webChat/getMessage",
                method: "get",
                success: (res) => {
                    this.list.push(...res.data);
                    this.$nextTick(() => {
                        let el = document.querySelector('.content-list');
                        el.scrollTop = el.scrollHeight;
                    })
                }
            })
        }
    }
}
</script>
<style lang="scss" scoped>
.btn-box {
    padding: 20px;
    text-align: right;
    display: flex;
    justify-content: space-between;
    padding-top: 0;
}

.ipt-box {
    padding: 20px;
}

.content-list {
    padding: 20px;
    max-height: 400px;
    overflow-y: auto;
    border: 1px solid #ccc;
    border-radius: 5px;
    margin: 20px;
    margin-bottom: 0;
    position: relative;

    li {
        padding-top: 10px;

        .title {
            font-size: 14px;
            font-weight: bold;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            color: #333;
        }

        .time {
            font-size: 12px;
            color: #999;
            padding-top: 5px;
        }

        .content {
            padding: 10px;
            background-color: #eee;
            border-radius: 5px;
            margin-top: 10px;
            word-wrap: break-word; /* 旧版属性，部分浏览器支持 */
            overflow-wrap: break-word; /* 标准属性，建议使用 */
        }
    }
}

.success-tips {
    position: fixed;
    right: 60px;

    .sport {
        display: inline-block;
        width: 10px;
        height: 10px;
        border-radius: 50%;
    }

    .sport-error {
        background-color: red;
    }

    .sport-success {
        background-color: green;
    }

    .error {
        color: red;
        font-size: 14px;
    }

    .success {
        color: green;
        font-size: 14px;
    }
}
</style>